/**
 * Created by sam on 16-10-19.
 */
var cheerio = require('cheerio');
var BufferHelper = require('bufferhelper');
var iconv = require('iconv-lite');
var https = require('https');
var utils = require('./utils');
var dao = require('./dao');
var common = require("../conf/common");

//替换所有
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};

function loadAzRank(obj, page, ep) {
    var url = common.getDomain()+"/s/ref=nb_sb_noss?url=search-alias%3D" + obj.category + "&field-keywords=" + obj.keyword.replaceAll(" ", "+") + "&page=" + page;
    var source = common.getSource();
    utils.getc(url,obj.num,function (html) {
    //get(url, function (html) {
        if (html == 'timeout') {
            console.log("Thread["+obj.num+"] keyword:" + obj.keyword + ",page:" + page);
            ep.emit("sleep", page);
        } else {
            var $ = cheerio.load(html);

            $(".s-result-item ").each(function (i) {
                var asin = $(this).attr("data-asin");
                var title = $("h2", $(this)).attr("data-attribute");
                //var price = $(".a-color-price",$(this)).first().text();
                var $price = $(".a-color-price", $(this)).first();
                var price = "";
                var cur = $(".sx-price-currency").first().text();

                if (cur == '') {
                    price = $price.text();
                } else {
                    var whole = $(".sx-price-whole").first().text();
                    var fraction = $(".sx-price-fractional").first().text();
                    price = cur + whole + "." + fraction;
                }


                var is_pro_price = $(".s-price", $(this)).parent().parent().find('.a-text-strike').text();
                var img = $("img", $(this)).attr('src');
                var brand = $(".a-color-secondary", $(this)).eq(1).text();
                var comm = $("span[name='" + asin + "']").next().text().replace(",", "").replace(",", "");
                var grade = $(".a-icon-star >span", $(this)).last().text().replace(" out of 5 stars", "");
                var rank = $(this).attr("id").replace("result_", "");

                var data = {
                    asin: asin,
                    title: title,
                    source:source,
                    price: price,
                    is_pro_price: is_pro_price == '' ? 0 : 1,
                    img: img,
                    brand: brand,
                    comm: comm,
                    grade: grade,
                    rank: parseInt(rank) + 1,
                    page: page,
                    index: i + 1,
                    category: obj.category,
                    keyword: obj.keyword,
                };

                /*console.log("page:"+obj.pageNum+",i:"+i+",keyword:"+obj.keyword+",asin:"+asin+",comm:"+comm);
                 console.log(" grade:"+grade+" ,rank:"+rank+",price:"+price+",brand:"+brand);*/
                //console.log(data)
                dao.saveRank(data);

            });

            if (page < 20) {
                ep.emit('next_page', obj);
            }else{
                ep.emit('next_word', obj);
            }
        }
    })
}

function loadAzAbsrRank(obj,ep) {
    var source = common.getSource();
    utils.getc(obj.url+"&ajax=1",obj.num,function (html) {
        if (html == 'timeout') {
            ep.emit("sleep",obj);
        } else {

            var $ = cheerio.load(html);

            $(".zg_itemImmersion").each(function () {
                var rank = $(".zg_rankNumber", $(this)).text().trim().replace(".", "");
                var title = $(".a-section .a-spacing-mini ", $(this)).next().attr("title");
                var img = $(".a-section .a-spacing-mini > img", $(this)).attr("src");
                var grade = $(".a-icon-star > span ", $(this)).text().replace(" out of 5 stars", "");
                var comm = $(".a-size-small .a-link-normal", $(this)).text().replaceAll(",","");
                var price = $(".a-color-price ", $(this)).text();
                var href = $(".a-link-normal", $(this)).first().attr("href");
                var metadata = $(".p13n-asin ", $(this)).attr("data-p13n-asin-metadata");
                var asin = JSON.parse(metadata).asin;

                //console.log("rank:" + rank + ",grade:" + grade + ",comm:" + comm + ",price:" + price + ",asin:" + asin);
                /* console.log("title:" + title);
                console.log("img:" + img);
                console.log("href:" + href);*/

                var data = {
                    num:obj.num,
                    url:obj.url,
                    source:source,
                    rank:rank,
                    grade:grade,
                    comm:comm,
                    price:price,
                    asin:asin,
                    category:obj.category,
                    pro_url:common.getDomain()+href,
                }
                dao.saveAbsrRank(data);
            });

            ep.emit('next_word', obj);
        }
    })
}


function get(url, fn) {
    var request_timer = null, req = null,flag = true,req_flag = true;
    // 请求5秒超时
    request_timer = setTimeout(function () {
        //req.abort();
        console.log('Request Timeout.');
        flag = false;
        req_flag = false;
        if (fn) fn('timeout');
    }, 5000);

    req = https.get(url, function (res) {
        clearTimeout(request_timer);

        // 等待响应6秒超时
        var response_timer = setTimeout(function () {
            res.destroy();
            console.log('Response Timeout.');
            flag = false;
            if (req_flag&&fn) fn('timeout');
        }, 10000);

        var bufferHelper = new BufferHelper();
        res.on('data', function (chunk) {
            bufferHelper.concat(chunk);
        });
        res.on('end', function () {
            clearTimeout(response_timer);
            var html = iconv.decode(bufferHelper.toBuffer(), 'utf-8');

            if (flag && req_flag && fn) fn(html);
        });
    });
}


//loadAzRank();

module.exports.loadAzRank = loadAzRank;
module.exports.loadAzAbsrRank = loadAzAbsrRank;

/*function test() {
    var url = "https://www.amazon.com/Best-Sellers-Cell-Phones-Accessories-Phone-Cases-Holsters-Clips/zgbs/wireless/2407760011/ref=zg_bs_pg_1?_encoding=UTF8&pg=1&ajax=1";
    loadAzAbsrRank(url);
     //get(url,function (data) {
     //console.log(data)
    // })
}*/

//test();


/*

 function _get(url,fn){
 var parse_u=require('url').parse(url,true);
 var isHttp=parse_u.protocol=='http:';
 var options={
 host:parse_u.hostname,
 port:parse_u.port||(isHttp?80:443),
 path:parse_u.path,
 method:'GET',
 headers:{
 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36 LBBROWSER'
 }
 };
 var req = require(isHttp?'http':'https').request(options,function(res){
 var _data='';
 res.on('data', function(chunk){
 _data += chunk;
 });
 res.on('end', function(){
 if(fn) fn(_data);
 });
 });
 req.end();
 }*/

/*

 var http = require('http');

 var request_timer = null, req = null;
 // 请求5秒超时
 request_timer = setTimeout(function() {
 req.abort();
 console.log('Request Timeout.');
 }, 5000);

 var options = {
 host: 'www.google.com',
 port: 80,
 path: '/'
 };
 req = http.get(options, function(res) {
 clearTimeout(request_timer);

 // 等待响应60秒超时
 var response_timer = setTimeout(function() {
 res.destroy();
 console.log('Response Timeout.');
 }, 60000);

 console.log("Got response: " + res.statusCode);
 var chunks = [], length = 0;
 res.on('data', function(chunk) {
 length += chunk.length;
 chunks.push(chunk);
 });
 res.on('end', function() {
 clearTimeout(response_timer);
 var data = new Buffer(length);
 // 延后copy*/
